<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

class Freelancer extends Authenticatable
{
    use HasFactory, HasApiTokens;

    public $incrementing = false;
    protected $keyType = 'string';

    public const VERIFICATION_PENDING = 'pending';
    public const VERIFICATION_APPROVED = 'approved';
    public const VERIFICATION_REJECTED = 'rejected';

    public const RECOGNITION_PENDING = 'pending';
    public const RECOGNITION_APPROVED = 'approved';
    public const RECOGNITION_REJECTED = 'rejected';

    protected $fillable = [
        'name',
        'phone',
        'email',
        'id_card',
        'bank_account',
        'bank_name',
        'gender',
        'education',
        'age',
        'address',
        'resume',
        'status',
        'verification_status',
        'id_card_recognition_status',
        'face_recognition_status',
        'last_login_at',
        'last_login_ip',
        'weixin_openid',
    ];

    protected $casts = [
        'id' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'last_login_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function (self $freelancer) {
            if (empty($freelancer->id)) {
                $freelancer->id = self::generateSnowflakeId();
            }
        });
    }

    public static function generateSnowflakeId(): string
    {
        $timestamp = (int) (microtime(true) * 1000);
        $machineId = mt_rand(0, 1023);
        $sequence = mt_rand(0, 4095);

        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;

        return (string) $snowflakeId;
    }


    /**
     * 所属租户
     */
    /**
     * 任务报名记录
     */
    public function applications()
    {
        return $this->hasMany(TaskApplication::class);
    }

    /**
     * 已报名的任务
     */
    public function tasks()
    {
        return $this->belongsToMany(Task::class, 'task_applications')
                    ->withPivot(['status', 'application_note', 'rejection_reason', 'applied_at', 'processed_at', 'processed_by'])
                    ->withTimestamps();
    }

    /**
     * 结算记录
     */
    public function settlements()
    {
        return $this->hasMany(Settlement::class);
    }

    public function wechatOpenids()
    {
        return $this->hasMany(WechatOpenid::class);
    }

    public function fourElementLogs()
    {
        return $this->hasMany(FreelancerFourElementLog::class);
    }

    /**
     * 检查是否符合任务要求
     */
    public function meetsTaskRequirements(Task $task)
    {
        // 性别要求
        if ($task->gender_requirement !== 'unlimited' && $this->gender !== $task->gender_requirement) {
            return false;
        }

        // 学历要求
        if ($task->education_requirement !== 'unlimited') {
            $educationLevels = ['junior_high', 'high_school', 'college', 'bachelor', 'master', 'doctor'];
            $requiredLevel = array_search($task->education_requirement, $educationLevels);
            $freelancerLevel = array_search($this->education, $educationLevels);
            
            if ($freelancerLevel < $requiredLevel) {
                return false;
            }
        }

        // 年龄要求
        if ($task->min_age && $this->age < $task->min_age) {
            return false;
        }
        if ($task->max_age && $this->age > $task->max_age) {
            return false;
        }

        return true;
    }
}
